<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>闭包</title>
</head>
<body>
    
</body>
<script>

    //闭包:通过在函数(fn1)内部定义函数(fn2)，来访问 fn1 的局部变量(x)
    function fn(){
        var x = 1;
        function fna(){
            return ++x;
        }
        return fna;
    }
    var result = fn();

    console.log(result());//2
    console.log(result());//3
    //闭包
    //形成闭包的条件: 外层定义的函数(addNumber),内层定义的函数(匿名),内层与外层作用域内相关联的变量
    function addNumber (start)//外层
    {
        return function(step)//内层
        {
            start += step;//start与start关联
            console.log('step: '+step);
            return start;
        }
    }
    var result = addNumber(10);//此时result接收的是内层函数，所以result接收的参数就是内层的step值
    console.log(result(10)); //20
    console.log(result(10)); //30
    console.log(result(1)); //31
    
    //内层与外层相关联的变量(start)没有释放，一直在内存中
    //作用:
    //①访问函数内部局部变量(start)
    //②可以让相关联的变量保持在内存中不释放

    function fn1 (){
        var i = 0;
        function fn2(){
            console.log(++i);
        }
        return fn2;
    }
    var fn3 = fn1();
    var fn4 = fn1();
    fn3();//1
    fn3();//2
    fn3();//3
    fn4();//1
    fn4();//2
</script>
</html>